import useTokenStore from '@/stores/token'

const timeout = 60 * 1000
const baseURL = import.meta.env.VITE_API_URL

interface Data<T> {
  code: number
  msg: string
  data: T
}
const tokenStore = useTokenStore()
const httpInterceptor = {
  invoke(options: UniApp.RequestOptions) {
    const isNotToken = options.header?.isToken === false
    options.header = options.header || {}
    if (!options.url.startsWith('http')) options.url = baseURL + options.url
    if (tokenStore.token && !isNotToken) options.header.Authorization = 'Bearer ' + tokenStore.token
  }
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

export default <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      timeout: options.timeout || timeout,
      success: res => {
        if (res.statusCode >= 200 && res.statusCode < 300 && (res.data as Data<T>).code !== 401) resolve(res.data as Data<T>)
        else if (res.statusCode === 401 || (res.data as Data<T>).code === 401) {
          tokenStore.clearToken()
          uni.navigateTo({ url: '/pages/login/index?code=401' })
          reject('登录状态已过期，请重新登录')
        }
        else {
          const msg = (res.data as Data<T>).msg || '请求失败'
          uni.showToast({
            title: msg,
            icon: 'none'
          })
          reject(msg)
        }
      },
      fail: err => {
        let msg = err.errMsg
        if (msg === 'request:fail') msg = '网络错误，换个网络试试'
        else if (msg.includes('timeout')) msg = '系统接口请求超时'
        uni.showToast({
          title: msg,
          icon: 'error'
        })
        reject(msg)
      }
    })
  })
}

export const upload = <T>(options: UniApp. UploadFileOption) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.uploadFile({
      ...options,
      name: options.name || 'file',
      timeout: options.timeout || timeout,
      success: res => {
        const date = JSON.parse(res.data);
        if (res.statusCode >= 200 && res.statusCode < 300) resolve(date as Data<T>)
        else if (res.statusCode === 401) {
          tokenStore.clearToken()
          uni.navigateTo({ url: '/pages/login/index?code=401' })
          reject('登录状态已过期，请重新登录')
        }
        else {
          const msg = date.msg || '上传失败'
          uni.showToast({
            title: msg,
            icon: 'none'
          })
          reject(msg)
        }
      },
      fail: err => {
        let msg = err.errMsg
        if (msg === 'request:fail') msg = '网络错误，换个网络试试'
        else if (msg.includes('timeout')) msg = '系统接口请求超时'
        uni.showToast({
          title: msg,
          icon: 'error'
        })
        reject(msg)
      }
    })
  })
}